package com.tomato.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.tomato.bean.Photo;
import com.tomato.dao.PhotoDao;

@SuppressWarnings("serial")
public class EbookServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		Long id = null;
		// display photo
		if (method.equals("show")) {
			id = Long.parseLong(req.getParameter("id"));
			if (id == null) {
				return;
			}
			Photo photo = PhotoDao.getInstance().getById(id);
			if (photo == null) {
				return;
			}
			Blob b = photo.getEbook();
			Blob image = photo.getImage();
			resp.setContentType("image/jpeg;charset=utf-8");
			resp.getOutputStream().write(image.getBytes());
			resp.getOutputStream().println("<text>");
			resp.getOutputStream().write(b.getBytes());
			resp.getOutputStream().close();
		}
		// xml photo
		if (method.equals("xml")) {
			// All_XML_List
			resp.setContentType("text/xml;charset=utf-8");
			resp.sendRedirect("ebookAllList.jsp");
			//resp.sendRedirect("ebookSelectList.jsp");
			/*
			 * id = Long.parseLong(req.getParameter("id")); if (id == 0 || id ==
			 * null) { resp.sendRedirect("index"); } if
			 * (req.getMethod().equals("GET")) { Photo photo = null; photo =
			 * PhotoDao.getInstance().getById(id); req.setAttribute("photo",
			 * photo); try { req.getRequestDispatcher("ebookAllList.jsp")
			 * .forward(req, resp); } catch (ServletException e) {
			 * e.printStackTrace(); } }
			 */
			/*
			 * id = Long.parseLong(req.getParameter("id")); if (id == null) {
			 * return; } Photo photo = PhotoDao.getInstance().getById(id); if
			 * (photo == null) { return; } Blob b = photo.getEbook();
			 * resp.setContentType("text/plain;charset=utf-8");
			 * resp.setHeader("Cahce-Control", "no-cache, must-realidate");
			 * resp.setHeader("Content-type", "application/xml;charset=utf-8");
			 * resp.getOutputStream().println("<?xml version=" + "\"1.0\"" +
			 * " encoding=" + "\"utf-8\"" + "?>");
			 * resp.getOutputStream().print("<text>");
			 * resp.getOutputStream().write(b.getBytes());
			 * resp.getOutputStream().print("<txt></txt>");
			 * resp.getOutputStream().write(photo.getEbook().getBytes());
			 * resp.getOutputStream().print("</text>");
			 * resp.getOutputStream().close();
			 */
		}
		// delete photo
		if (method.equals("delete")) {
			id = Long.parseLong(req.getParameter("id"));
			PhotoDao.getInstance().deleteById(id);
			resp.sendRedirect("index");
		}
		// edit
		if (method.equals("edit")) {
			id = Long.parseLong(req.getParameter("id"));
			if (id == 0 || id == null) {
				resp.sendRedirect("index");
			}
			if (req.getMethod().equals("GET")) {
				Photo photo = null;
				photo = PhotoDao.getInstance().getById(id);
				req.setAttribute("photo", photo);
				try {
					req.getRequestDispatcher("ebookEdit.jsp")
							.forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// upload photo and save in datastore
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		String author = null;
		String description = null;
		String genre = null;
		String title = null;
		Blob bEbook = null;
		if (method.equals("upload")) {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setHeaderEncoding("utf-8");
			FileItemIterator iterator = null;
			try {
				iterator = upload.getItemIterator(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			try {
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream stream = item.openStream();
					if (item.isFormField()) {
						// Handle form field
						if (item.getFieldName().equals("author")) {
							author = Streams.asString(stream);
						}
						if (item.getFieldName().equals("description")) {
							description = Streams.asString(stream);
						}
						if (item.getFieldName().equals("genre")) {
							genre = Streams.asString(stream);
						}
						if (item.getFieldName().equals("title")) {
							title = Streams.asString(stream);
						}
					} else {
						// Handle the uploaded file
						if (item.getFieldName().equals("ebook")) {
							bEbook = new Blob(IOUtils.toByteArray(stream));
						}
						Date date = new Date();

						Photo photo = new Photo(title, author, genre,
								description, date, bEbook);

						PhotoDao.getInstance().insertPhoto(photo);
						resp.sendRedirect("index");
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
		// edit and update photo property
		if (method.equals("edit")) {
			Long id = null;
			Blob bImage = null;
			ServletFileUpload upload = new ServletFileUpload();
			upload.setHeaderEncoding("utf-8");
			FileItemIterator iterator = null;
			try {
				iterator = upload.getItemIterator(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			try {
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream stream = item.openStream();
					if (item.isFormField()) {
						if (item.getFieldName().equals("id")) {
							id = Long.parseLong(Streams.asString(stream));
						}
					} else {
						// Handle the uploaded file
						/*
						if (item.getFieldName().equals("image")) {
							bImage= new Blob(IOUtils.toByteArray(stream));
						}*/
						bImage = new Blob(IOUtils.toByteArray(stream));
						
						Photo photo = new Photo(id, bImage);

						PhotoDao.getInstance().update(photo);
						resp.sendRedirect("index");
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
	}
}
